<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-form ref="searchData" size="medium" label-width="100px">
        <el-col :span="8">
          <el-form-item label="科室" prop="deptId">
            <el-select v-model="deptId" placeholder="请选择科室">
              <el-option v-for="(item, index) in depts" :key="index" :label="item.deptName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="时间" prop="range">
            <el-select v-model="searchData.day" placeholder="请选择">
              <el-option label="最近7天" :value="0"></el-option>
              <el-option label="下周" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="searchData.status">
              <el-radio :label="-1">全部</el-radio>
              <el-radio :label="0">编辑</el-radio>
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">暂停</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <p style="padding: 5px 0; margin-top: 0;margin-bottom: 25px;">
      <span style="float: left">编辑:</span>
      <span style="display: block;background-color: #409EFF;width: 20px;float: left;margin-right: 10px">&nbsp;</span>
      <span style="float: left">启用:</span>
      <span style="display: block;background-color: #67C23A;width: 20px;float: left;margin-right: 10px">&nbsp;</span>
      <span style="float: left">暂停:</span>
      <span style="display: block;background-color: #C0C4CC;width: 20px;float: left;margin-right: 10px">&nbsp;</span>
    </p>

    <el-table
      ref="table"
      :data="dataList"
      max-height="550"
      @cell-click="edit"
      style="width: 100%;">
      <el-table-column
        fixed
        headerAlign="center"
        align="center"
        prop="userName"
        label="姓名">
      </el-table-column>
      <el-table-column label="排班日期" headerAlign="center">
        <el-table-column v-for="(date,index) in dateList" :key="index"
                         headerAlign="center"
                         :label="date.d + ' ' + date.w"
                         min-width="120">
          <el-table-column label="上午" headerAlign="center" :prop="date.d + 'am'" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row[date.d + 'am'] && scope.row[date.d + 'am'].total"
                   :class="'status'+ scope.row[date.d + 'am'].status ">
                <p>名额:{{ scope.row[date.d + 'am'].total }}</p>
                <p>
                  {{ scope.row[date.d + 'am'] | timeFormat }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="下午" headerAlign="center" :prop="date.d + 'pm'" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row[date.d + 'pm'] && scope.row[date.d + 'pm'].total"
                   :class="'status'+ scope.row[date.d + 'pm'].status ">
                <p>名额:{{ scope.row[date.d + 'pm'].total }}</p>
                <p>
                  {{ scope.row[date.d + 'pm'] | timeFormat }}
                </p>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="scheduleVisible" title="编辑排班">
      <el-form ref="elForm" :model="targetItem" size="medium" label-width="100px">
        <el-form-item label="医生名称" prop="userName">
          <!--<el-input v-model="targetItem.userName" placeholder="医生名称" readonly clearable
                    :style="{width: '100%'}"></el-input>-->
          <p style="margin: 0">{{targetItem.userName}}</p>
        </el-form-item>
        <el-form-item label="排班时间" prop="date">
          <!--<el-input v-model="targetItem.date" placeholder="请输入排班时间" readonly clearable :style="{width: '100%'}">
          </el-input>-->
          <p style="margin: 0">{{targetItem.date}}</p>
        </el-form-item>
        <el-form-item label="排班时间" prop="time">
          <el-time-select
            placeholder="起始时间"
            v-model="targetItem.beginTime"
            @blur="chooseBeginTime"
            :picker-options="{
              start: start,
              step: '00:15',
              end: end
            }">
          </el-time-select>
          <el-time-select
            placeholder="结束时间"
            v-model="targetItem.endTime"
            :picker-options="{
              start: targetItem.beginTime,
              step: '00:15',
              end: end,
              minTime: targetItem.beginTime
            }">
          </el-time-select>
          <!--<el-time-picker v-model="targetItem.time" is-range format="HH:mm:ss" value-format="HH:mm:ss" step="'00:15'"
                          :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                          clearable></el-time-picker>-->
        </el-form-item>
        <el-form-item label="名额" prop="total">
          <el-input-number v-model="targetItem.total" placeholder="名额" :step='1'></el-input-number>
        </el-form-item>
        <el-form-item label="班次" prop="noon">
          <p style="margin: 0">{{targetItem.noon| showNoon}}</p>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-radio-group v-model="targetItem.status">
            <el-radio :label="0">编辑</el-radio>
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getNextWeek, getDayWeek, formatDate} from "@/utils/date";
  import {getDept, getDeptUsers} from "@/api/dept";
  import {getScheduling, editScheduling} from "@/api/scheduling";

  export default {
    data() {
      return {
        start:"08:30",
        end:"12:00",
        targetItem: {
          userName: undefined,
          date: undefined,
          time: null,
          beginTime: null,
          endTime: null,
          total: undefined,
          noon: undefined,
          available: false
        },
        scheduleVisible: false,
        users: [],
        deptId: null,
        searchData: {
          day: 0,
          status: -1
        },
        depts: [],
        dateList: [],
        dataList: [{
          "userName": "niki",
          "dept": "眼科部门",
          "beginTime": "09:00:00",
          "endTime": "12:00:00",
          "date": "2020-5-26",
          "noon": "pm",
          "status": 1,
          "total": 10
        }]
      }
    },
    filters: {
      timeFormat(p) {
        if (!p.beginTime || !p.endTime) {
          return
        }
        return p.beginTime.substr(0, 5) + "-" + p.endTime.substr(0, 5)
      },
      showNoon(n) {
        return n === "am" ? "上午" : "下午"
      }
    },
    watch: {
      deptId(val) {
        console.log(val)
        this.getUsers()
      },
      day() {
        console.log(this.day)
        this.dateList = this.day === 0 ? getDayWeek() : getNextWeek();
        this.searchScheduling();
      },
      status() {
        console.log(this.status)
        this.searchScheduling();
      }
    },
    computed: {
      day() {
        return this.searchData.day
      },
      status() {
        return this.searchData.status
      }
    },
    created() {
      window.app = this
      this.dateList = getDayWeek();
      this.searchScheduling();
      this.searchDept();
    },
    methods: {
      chooseBeginTime(){
      },
      close() {
        this.$emit('update:visible', false)
        this.scheduleVisible = false
      },
      handelConfirm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          /*this.targetItem.beginTime = this.targetItem.time[0];
          this.targetItem.endTime = this.targetItem.time[1];*/
          console.log(this.targetItem);
          let data = {
            "id": this.targetItem.id,
            "beginTime": this.targetItem.beginTime + ":00",
            "scheduleDate": this.targetItem.date,
            "deptId": this.targetItem.deptId,
            "endTime": this.targetItem.endTime + ":00",
            "scheduleNoon": this.targetItem.noon,
            "total": this.targetItem.total,
            "userId": this.targetItem.userId,
            "status": this.targetItem.status
          }
          console.log(data);
          editScheduling([data]).then(response => {
            if (response.code === 200) {
              console.log(response)
            }
          });
          this.close()
        })
      },
      edit(row, column, cell, event) {
        if (row) {
          console.log(row[column.property]);
          console.log(column.property);
          this.scheduleVisible = true
          if (!row[column.property]) {
            row[column.property] = {}
          }
          this.targetItem = row[column.property];
          this.targetItem.userName = row.userName
          this.targetItem.date = row.date
          if (!this.targetItem.deptId) {
            this.targetItem.deptId = row.deptId
          }
          if (!this.targetItem.userId) {
            this.targetItem.userId = row.doctorId
          }
          this.targetItem.date = column.property.substr(0, 10)
          this.targetItem.noon = column.property.substr(10)

          if (this.targetItem.noon === "am") {
              this.start = "08:30";
              this.end = "12:00";
          }else{
            this.start = "12:30";
            this.end = "19:00";
          }

          if (this.targetItem.beginTime && this.targetItem.endTime) {
            this.targetItem.time = [this.targetItem.beginTime, this.targetItem.endTime]
          }
        }

      },
      searchDept() {
        getDept({}).then(response => {
          if (response.code === 200) {
            this.depts = response.data
          } else {
            this.depts = []
          }
        })
      },
      searchScheduling() {
        getScheduling({scheduleDate: this.dateList[0].d, status: this.searchData.status}).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list
            let map = {}
            this.dataList.forEach(p => {
              if (!map[p.doctorName]) {
                p.userName = p.doctorName;
                p.dept = p.deptName;
                p.userId = p.doctorId;
                p.dept = p.deptName;
                map[p.doctorName] = p
              }
              // let d = formatDate(p.scheduleDate, "yyyy-MM-dd");
              map[p.doctorName][p.scheduleDate + p.scheduleNoon] = {
                id: p.id,
                total: p.total,
                date: p.scheduleDate,
                noon: p.scheduleNoon,
                beginTime: p.beginTime,
                endTime: p.endTime,
                userId: p.doctorId,
                deptId: p.deptId,
                status: p.status,
              }
            })
            this.dataList = []
            for (let k in map) {
              this.dataList.push(map[k])
            }
          } else {
            this.dataList = []
          }
          if (this.users) {
            this.showSchedule()
          }
        })
      },
      showSchedule() {
        let _that = this;
        this.users.forEach(user => {
          let item = {
            "userId": user.userId,
            "userName": user.niceName,
            "deptId": user.deptId,
            "dept": user.deptName
          }
          let _flag = false;
          _that.dataList.forEach(schedule => {
            if (schedule.userId === user.userId) {
              _flag = true;
              return;
            }
          })
          if (!_flag) {
            _that.dataList.push(item);
            this.dateList.forEach(time => {
              item.date = time.d
              item[time.d + "am"] =
                {
                  status: 0,
                  userId: user.userId,
                  deptId: user.deptId,
                  date: time.d,
                  noon: "am",
                  total: null,
                  beginTime: null,
                  endTime: null,
                  time: null
                }
              item[time.d + "pm"] =
                {
                  status: 0,
                  userId: user.userId,
                  deptId: user.deptId,
                  date: time.d,
                  noon: "pm",
                  total: null,
                  beginTime: null,
                  endTime: null,
                  time: null
                }
            })
          }
        })
      },
      getUsers() {
        getDeptUsers({"deptId": "" + this.deptId}).then(response => {
          if (response.code === 200) {
            this.users = response.page.list;
            // this.dataList = [];
            this.showSchedule();
          }
        })
      }
    }
  }
</script>

<style scoped>
  .status0 {
    color: #409EFF;
  }

  .status1 {
    color: #67C23A;
  }

  .status2 {
    color: #C0C4CC;
  }
</style>
